package main

import (
	"errors"
	"fmt"
	"net"
	"net/http"
	"net/rpc"
	"time"

	"gitee.com/distribute_system/heartbeats/idl"
	"gitee.com/distribute_system/heartbeats/utils"
)

var (
	MasterServer *rpc.Client
)

func MustInit(address string) {
	var err error
	MasterServer, err = rpc.DialHTTP("tcp", address)
	if err != nil {
		panic(err)
	}
}

func Ping() (err error) {
	req := idl.HeartBeatsRequest{}
	resp := new(idl.HeartBeatsResponse)

	req.Info = new(idl.NodeInfo)
	req.Info.Address = "127.0.0.1:6790"
	err = MasterServer.Call("Service.Ping", req, resp)
	if err != nil {
		fmt.Printf("Ping Server Error, err = %v\n", err)
		return err
	}
	return nil
}

type Client struct {
}

func (c *Client) Pong(req idl.PongRequest, resp *idl.PongResponse) (err error) {
	if resp == nil {
		return errors.New("参数错误")
	}

	resp.Message = "Pong"
	return nil
}

func main() {
	defer func() {
		MasterServer.Close()
	}()

	MustInit("127.0.0.1:6789")
	rpc.Register(new(Client))
	rpc.HandleHTTP()

	l, err := net.Listen("tcp", "127.0.0.1:6790")
	if err != nil {
		panic(err)
	}

	utils.ScheduleAtFixedRate(func() {
		Ping()
	}, 0, 5, time.Second)
	http.Serve(l, nil)
	return
}
